package de.zainodis.triplog.ui.fragment;

import android.app.Fragment;
import android.app.LoaderManager;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import de.zainodis.triplog.R;
import de.zainodis.triplog.data.share.TriplogContract;
import de.zainodis.triplog.data.share.WeatherEntryPersister;
import de.zainodis.triplog.util.DateTimeUtils;
import de.zainodis.triplog.util.Utilities;

/**
 * Created by fzarrai on 8/25/2014.
 */
public class WeatherForecastDetailFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
    /**
     * Use this to pass the row id of the target WeatherReport as an int via the extras bundle
     */
    public static final String WEATHER_REPORT_ID = "WeatherReportId";

    private static final String SAVED_INSTANCE_KEY_ROW_ID = "rowId";
    private static final int FORECAST_DETAIL_LOADER_ID = 1;
    //Row id of the report we intend to load
    private long reportId;

    public WeatherForecastDetailFragment() {
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {

        if (savedInstanceState != null) {
            //Restore instance variables
            reportId = savedInstanceState.getLong(SAVED_INSTANCE_KEY_ROW_ID);
        } else {
            //Retrieve weather report id
            Bundle bundle = getArguments();
            if (bundle != null && bundle.containsKey(WeatherForecastDetailFragment.WEATHER_REPORT_ID)) {
                reportId = bundle.getInt(WeatherForecastDetailFragment.WEATHER_REPORT_ID);
                //We initialize the loader here which is bound to the activity lifecycle
                getLoaderManager().initLoader(FORECAST_DETAIL_LOADER_ID, null, this);
            }
        }
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putLong(SAVED_INSTANCE_KEY_ROW_ID, reportId);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_detail, container, false);
        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();
        Bundle bundle = getArguments();
        //Check to avoid unnecessary reloads
        if (bundle != null && bundle.containsKey(WeatherForecastDetailFragment.WEATHER_REPORT_ID)) {
            reportId = bundle.getInt(WeatherForecastDetailFragment.WEATHER_REPORT_ID);
            //We initialize the loader here which is bound to the activity lifecycle
            getLoaderManager().restartLoader(FORECAST_DETAIL_LOADER_ID, null, this);
        }
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {

        Uri forecastUri = TriplogContract.buildWeatherUri(reportId);
        //Since we query by row id, this should only yield one result
        return new CursorLoader(getActivity(), forecastUri, WeatherEntryPersister.WEATHER_COLUMNS, null, null, null);
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
        //TODO show data
        View view = getView();
        if (cursor != null && cursor.moveToFirst()) {

            String max = cursor.getString(WeatherEntryPersister.COLUMN_INDEX_MAX_TEMP);
            String min = cursor.getString(WeatherEntryPersister.COLUMN_INDEX_MIN_TEMP);
            String description = cursor.getString(WeatherEntryPersister.COLUMN_INDEX_DESCRIPTION);
            String date = cursor.getString(WeatherEntryPersister.COLUMN_INDEX_DATE);
            float wind = cursor.getFloat(WeatherEntryPersister.COLUMN_INDEX_WIND_SPEED);
            float humidity = cursor.getFloat(WeatherEntryPersister.COLUMN_INDEX_HUMIDITY);
            int iconId = cursor.getInt(WeatherEntryPersister.COLUMN_INDEX_ICON_ID);

            String day = DateTimeUtils.getDayOfWeek(DateTimeUtils.dbDateStringToDate(date));
            date = DateTimeUtils.fromDbDateString(date);

            //Load the view with data
            TextView dateView = (TextView) view.findViewById(R.id.fragment_detail_date);
            dateView.setText(date);


            //Convert temperatures if need be
            String unit = Utilities.getPreferredUnit(getActivity());
            String displayedUnit = null;
            if (getActivity().getString(R.string.pref_value_imperial).equals(unit)) {
                //Convert data to imperial and change symbol
                max = String.valueOf(Utilities.celsiusToFahrenheit(Integer.parseInt(max)));
                min = String.valueOf(Utilities.celsiusToFahrenheit(Integer.parseInt(min)));
                displayedUnit = "°F";
            } else {
                //Data is already metric, just change the symbol
                displayedUnit = "°C";
            }

            TextView maxTemp = (TextView) view.findViewById(R.id.fragment_detail_max);
            maxTemp.setText(String.format("%s %s", max, displayedUnit));

            TextView minTemp = (TextView) view.findViewById(R.id.fragment_detail_min);
            minTemp.setText(String.format("%s %s", min, displayedUnit));

            TextView humidityView = (TextView) view.findViewById(R.id.fragment_detail_humidity);
            humidityView.setText(String.format("%s %s%%", getString(R.string.humidity), String.valueOf(humidity)));

            //Convert wind speed
            if (getActivity().getString(R.string.pref_value_imperial).equals(unit)) {
                //Convert data to imperial and change symbol
                wind = Math.round(Utilities.kmhToMph(wind));
                displayedUnit = "mp/h";
            } else {
                //Data is already metric, just change the symbol
                displayedUnit = "km/h";
            }

            TextView windView = (TextView) view.findViewById(R.id.fragment_detail_wind);
            windView.setText(String.format("%s %s %s", getString(R.string.wind), wind, displayedUnit));

            int resourceIconId = Utilities.getWeatherIconId(iconId);
            if (resourceIconId > 0) {
                ImageView iconView = (ImageView) view.findViewById(R.id.fragment_detail_image);
                iconView.setImageDrawable(getResources().getDrawable(resourceIconId));
                iconView.setContentDescription(String.format("%s, %s, %s to %s", date, description, min,max));
            }

        } else {
            //TODO inform user that no results are available
        }

    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
    }


}
